const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");

//存储账户信息
let userMsg = [];

http.createServer((req,res)=>{
    if(req.url !== "/favicon.ico"){
        if(url.parse(req.url).pathname === "/api"){
            loginAndRegHandle(req, res);
        }else{
            fileHandle(req, res);
        }
    }
}).listen("4000");

// 登陆/注册请求
function loginAndRegHandle(req, res){
    const urlObj = url.parse(req.url, true);
    let str = "";
    req.on("data",(d)=>{
        str += d;
    })
    req.on("end",()=>{
        let reqObj = null;
        if(str === ""){
            reqObj = urlObj.query;
        }else{
            reqObj = qs.parse(str);
        }
        if(reqObj.type === "login"){
            //登录
            login(reqObj,res);
        }else{
            //注册
            registers(reqObj, res);
        }
    })
}
//登录
function login(data,res){
    let i = 0;
    let onoff = userMsg.some((val,idx)=>{
        i = idx;
        return (val.tel === data.username) || (val.mail === data.username);
    })
    if(onoff){
        //有账号，判断密码是否相同
        if(userMsg[i].pas === data.pas){
            //相等
            res.write(JSON.stringify({code:1,title:"登录成功",data:userMsg[i]}));
            userMsg[i].flag = 1;
        }else{
            res.write(JSON.stringify({code:2,title:"密码错误"}));
        }
    }else{
         // 没有用户名，未注册
         res.write(JSON.stringify({code:0,title:"用户名不存在"}))
    }
    res.end();
};
//注册
function registers(data, res){
    let onoff = userMsg.some(val=>{
        return val.tel === data.tel;
    })
    if(onoff){
        //用户名重复
        res.write(JSON.stringify({code:0,title:"用户名重复"}))
    }else{
        userMsg.push({
            userid:"userid_"+Math.random().toString().slice(2),
            tel:data.tel,
            pas:data.pas,
            mail:data.mail,
            flag:0
        })
        res.write(JSON.stringify({code:1,title:"注册成功"}))
    }
    res.end();
};
// 文件加载
function fileHandle(req, res){
    fs.readFile("./www" + url.parse(req.url).pathname,(err, data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}